package client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;

import org.apache.log4j.Logger;

public class CloudKeeper2 extends Thread {
	private static final Logger logger = Logger.getLogger(CloudKeeper2.class);
	private Selector selector;

	public CloudKeeper2() throws IOException {
		this.selector = Selector.open();
	}

	public void run() {
		try {
			SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 10055));
			socketChannel.configureBlocking(false);
			socketChannel.register(this.selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

			selector.select(1000);
			Set<SelectionKey> s_selectionKey;
			synchronized (this) {
				s_selectionKey = selector.selectedKeys();
			}
			ArrayList<SelectionKey> l_selectionKey = new ArrayList<SelectionKey>(s_selectionKey);
			Collections.shuffle(l_selectionKey);
			for (SelectionKey selectionKey : l_selectionKey) {
				if ((selectionKey.readyOps() & SelectionKey.OP_WRITE) != 0) {
					doWrite(selectionKey);
				} else if ((selectionKey.readyOps() & SelectionKey.OP_READ) != 0) {
					// doRead(selectionKey);
				}
			}
			s_selectionKey.clear();
		} catch (Exception e) {
			logger.error("error : " + e, e);
		}
	}

	public void doWrite(SelectionKey selectionKey) throws IOException {
		SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
		ByteBuffer byteBuffer = ByteBuffer.allocate(4);
		byteBuffer.putInt(130);
		byteBuffer.flip();
		socketChannel.write(byteBuffer);
		socketChannel.close();
	}

	public void doRead(SelectionKey selectionKey) {

	}

	public static void main(String[] args) throws IOException {
		(new CloudKeeper2()).start();

		/*
		 * InputStream is = socket.getInputStream();
		 * OutputStream os = socket.getOutputStream();
		 * 
		 * CreateMsg msg = new CreateMsg("/c/d/e/f/g", "this is content");
		 * 
		 * os.write(msg.encode());
		 * socket.shutdownOutput();
		 * 
		 * int count;
		 * byte[] buffer = new byte[1024];
		 * while ((count = is.read(buffer)) != -1) {
		 * System.out.println(new String(buffer, 0, count));
		 * }
		 * 
		 * socket.close();
		 */
	}
}